<?php

// +---------------------------------------------------------------------------+
// | This file is part of the core package.                                    |
// | Copyright (c) laiketui.com                                                |
// |                                                                           |
// | For the full copyright and license information, please view the LICENSE   |
// | file that was distributed with this source code. You can also view the    |
// | LICENSE file online at http://www.laiketui.com                            |
// +---------------------------------------------------------------------------+
namespace keengine\database;

use keengine\exception\DatabaseException;
use think\facade\Db;

/**
 * 使用ThinkPHP的ORM类库 topthink/think-orm
 *
 * @package    laiketui
 * @subpackage database
 *
 * @author ketter (ketter@laiketui.com)
 * @since  3.0.0
 */
class ThinkDatabase extends Database
{

    //初始化Thinkphp-orm
    public function initialize ($parameters = null)
    {

        parent::initialize($parameters);

        // determine how to get our
        $method = $this->getParameter('method', 'normal');

        switch ($method)
        {

            case 'normal':

                // get parameters normally
                $type     = $this->getParameter('type');
                $prefix   = $this->getParameter('prefix');
                $debug    = $this->getParameter('debug');
                $database = $this->getParameter('database');
                $host     = $this->getParameter('host', '127.0.0.1');
                $password = $this->getParameter('password');
                $user     = $this->getParameter('user');
                $port     = $this->getParameter('port','3306');
                $charset  = $this->getParameter('charset','utf8');
                $deploy  = $this->getParameter('deploy','0');
                $rw_separate  = $this->getParameter('rw_separate','false');
                $read_master  = $this->getParameter('read_master','false');

                break;

            case 'server':

                // construct a connection string from existing $_SERVER values
                // and extract them to local scope
                $parameters =& $this->loadParameters($_SERVER);
                extract($parameters);

                break;

            case 'env':

                // construct a connection string from existing $_ENV values
                // and extract them to local scope
                $parameters =& $this->loadParameters($_ENV);
                extract($parameters);

                break;

            default:

                // who knows what the user wants...
                $error = 'Invalid MySQLDatabase parameter retrieval method ' .
                    '"%s"';
                $error = sprintf($error, $method);

                throw new DatabaseException($error);

        }

        try {
            // 数据库配置信息设置（全局有效）
            Db::setConfig([
                // 默认数据连接标识
                'default'     => $type,
                // 数据库连接信息
                'connections' => [
                    $type => [
                        'deploy'   => $deploy,
                        // 数据库类型
                        'type'     => $type,
                        // 主机地址
                        'hostname' => $host,
                        // 用户名
                        'username' => $user,
                        'password' => $password,
                        // 数据库名
                        'database' => $database,
                        // 数据库编码默认采用utf8
                        'charset'  => $charset,
                        // 数据库表前缀
                        'prefix'   => $prefix,
                        // 数据库调试模式
                        'debug'    => $debug,
                        'hostport' => $port,
                        //读写分离
                        'rw_separate' => $rw_separate,
                        // 开启自动主库读取
                        'read_master' => $read_master,
                    ],
                ],
            ]);


        } catch (PDOException $e) {
            // the connection's foobar'd
            $error = 'Failed to create a MySQLDatabase connection';

            throw new DatabaseException($error);
        }

    }

    function connect()
    {

        try {

            $this->connection = Db::connect();

        } catch (PDOException $e) {
            // the connection's foobar'd
            $error = 'Failed to create a MySQLDatabase connection';

            throw new DatabaseException($error);
        }

        // make sure the connection went through
        if ($this->connection === false)
        {

            // the connection's foobar'd
            $error = 'Failed to create a MySQLDatabase connection';

            throw new DatabaseException($error);

        }

        // since we're not an abstraction layer, we copy the connection
        // to the resource
        $this->resource =& $this->connection;
    }

    /**
     * @inheritDoc
     */
    function shutdown()
    {
        if ($this->connection != null)
        {

            $this->connection = null;

        }
    }
}